import type { StudentWordItem, StudentWordShorthandStudyWordItem } from '@/api/types/student'
import { useUnitStudyWordsStore } from '@/stores/modules/useUnitStudyWordsStore'
import { deepClone } from '@/utils/common'
import { ref } from 'vue'

export function useStudyWords() {
  const unitStudyWordsStore = useUnitStudyWordsStore()

  // 在子组件中创建响应式的words数据
  const localWords = ref<StudentWordItem[]>([])
  const activeWordId = ref<string | number | null>(null)
  const currentIndex = ref(0)

  const formatLocalWords = (words: StudentWordItem[]) => {
    words.forEach((item) => {
      item.known = null
    })
    return words
  }

  // 格式化学习参数
  function formatStudyParams(words: StudentWordItem[]): StudentWordShorthandStudyWordItem[] {
    const _words = deepClone(words)
    return _words.map((item) => {
      return {
        wordId: item.wordId,
        clickNum: 0,
        correctNum: 0,
        wrongNum: 0,
      }
    })
  }

  // 初始化学习单词
  function initStudyWords(words: StudentWordItem[]) {
    localWords.value = formatLocalWords([...words])
    const studyWords = formatStudyParams(words)
    unitStudyWordsStore.updateStudyWords(studyWords)
    return studyWords
  }

  // 更新单词点击次数
  function updateWordClickNum(wordId: string | number) {
    const studyWords = unitStudyWordsStore.studyWords
    const wordItem = studyWords.find(item => item.wordId === wordId)
    if (!wordItem) {
      return
    }
    wordItem.clickNum = wordItem.clickNum ? wordItem.clickNum + 1 : 1
    localWords.value = localWords.value.map(item => item.wordId === wordId ? { ...item, clickNum: wordItem.clickNum } : item)
    unitStudyWordsStore.updateStudyWords(studyWords)
  }

  // 随机打乱单词顺序
  function randomizeWords() {
    // 使用 Fisher-Yates 洗牌算法打乱数组
    const shuffled = [...localWords.value]
    for (let i = shuffled.length - 1; i > 0; i--) {
      const j = Math.floor(Math.random() * (i + 1));
      [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]]
    }
    localWords.value = shuffled
    // 取消选中状态
    activeWordId.value = null
    // 重置索引
    currentIndex.value = 0
  }

  // 设置激活的单词
  function setActiveWord(wordId: string | number) {
    activeWordId.value = wordId
  }

  return {
    localWords,
    activeWordId,
    currentIndex,
    initStudyWords,
    updateWordClickNum,
    randomizeWords,
    setActiveWord,
  }
}
